<?php
/**
 * 处理国际支付宝扫码支付
 * Author: lyun
 * Date: 2018/4/20
 * Created by Panxsoft.
 */


namespace App\Services\Omnipay;

use App\Http\Controllers\Api\V1\App\Order\PayNotifyController;
use App\Models\Extension\Extension;
use App\Models\Order\Order;
use App\Models\Setting;
use App\Services\Orders\PayNotifyService;
use App\Services\Utils\TimeHelper;
use Omnipay\GlobalAlipay\AppGateway;
use Omnipay\Omnipay;
use Omnipay\GlobalAlipay\Message\AppPurchaseResponse;

class AliPayGlobal
{
    /**
     *  国际支付的配置
     *
     * @return AppGateway
     * @throws \Exception
     */
    public static function getAliGateWay()
    {
        /** @var AppGateway $gateway */
        $gateway = Omnipay::create('GlobalAlipay_App');

        $config = Setting::findConfigByCode(Setting::CODE_PAYMENT_ALI);

        // todo 验签都是RSA, 可能要单独申请国际支付宝账号。
        $gateway->setPartner('123456');
        $gateway->setSellerId($config['payment_alipay_app_id']);
        $gateway->setPrivateKey($config['payment_alipay_merchant_private_key']);
        $gateway->setAlipayPublicKey($config['payment_alipay_alipay_public_key']);
        $gateway->setNotifyUrl('http://example.com/notify');

        return $gateway;
    }

    /**
     *  国际支付宝，生成验签数据返回给App
     *
     * @param Order $order
     *
     * @return mixed|bool
     * @throws \Exception
     */
    public static function getConfig(Order $order)
    {
        $gateway = self::getAliGateWay();

        /** 创建订单 */
        $query_order = [
            'subject'      => $order->store_name,
            'out_trade_no' => $order->trade_no,
            'total_fee'    => self::getAliPayAmount($order), //order total fee
            'currency'     => $order->currency_code,
            'body'         => 'description',
        ];

        /** @var AppPurchaseResponse $response */
        $response = $gateway->purchase($query_order)->send();

        return $response->getOrderString();
    }

    /**
     *  支付宝支付成功的回调通知处理
     *
     * @return bool
     * @throws \Exception
     */
    public static function aliNotify()
    {
        logger(request()->all());
        $gateway = self::getAliGateWay();

        $request = $gateway->completePurchase();
        $request->setParams(array_merge($_POST, $_GET));

        try {
            /** @var \Omnipay\Alipay\Responses\AopCompletePurchaseResponse $response */
            $response = $request->send();

            if ($response->isPaid()) {  // Payment is successful
                $data['response'] = $request->getParams();
                $data['notify'] = $response->getResponseText(); // The response should be 'success' only
                /**
                 * @see responseDataMock
                 */
                logger($data);

                $out_trade_no = $data['response']['out_trade_no']; // 订单号

                /** @var Order $order */
                $order = Order::findOrderUnpaidByTradeNo($out_trade_no);

                if (!$order) return $data; // 没找到/已完成支付

                (new PayNotifyService)->savePaidStatus($order);

                return $data;
            } else {
                /**
                 * Payment is not successful
                 */
                return false;

            }
        } catch (\Exception $e) {
            /**
             * Payment is not successful
             */
            return false;
        }
    }

    /**
     * @param Order $order
     * @return mixed
     */
    private static function getAliPayAmount(Order $order)
    {
        $total_amount = $order->orderTotalByTotal->value;
        return config('pkx.ali.debug_pay_yuan') ?: sprintf('%.2f', $total_amount);
    }

    /**
     * @return array
     */
    public function responseDataMock()
    {
        return [
            'response' => [
                'gmt_create'       => '2018-12-04 17:40:31',
                'charset'          => 'UTF-8',
                'seller_email'     => 'panxsoft@outlook.com',
                'subject'          => 'Direwolf F2B 商城',
                'sign'             => 'ppT02kZWk69Vli2jlXuouzYyvDMWEqXE ...',
                'buyer_id'         => '2088012860633175',
                'invoice_amount'   => '0.01',
                'notify_id'        => '2018120400222174032033171034638408',
                'fund_bill_list'   => '[{"amount":"0.01","fundChannel":"ALIPAYACCOUNT"}]',
                'notify_type'      => 'trade_status_sync',
                'trade_status'     => 'TRADE_SUCCESS',
                'receipt_amount'   => '0.01',
                'app_id'           => '2016081501751560',
                'buyer_pay_amount' => '0.01',
                'sign_type'        => 'RSA2',
                'seller_id'        => '2088021952506112',
                'gmt_payment'      => '2018-12-04 17:40:31',
                'notify_time'      => '2018-12-05 18:04:50',
                'version'          => '1.0',
                'out_trade_no'     => '20181204012813392202',
                'total_amount'     => '0.01',
                'trade_no'         => '2018120422001433171010811152',
                'auth_app_id'      => '2016081501751560',
                'buyer_logon_id'   => '920***@qq.com',
                'point_amount'     => '0.00',
            ],
            'notify'   => 'success',
        ];
    }
}
